import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'  //必须导入

Vue.use(VueRouter)

const routes = [
    // { path: "/", name: 'login', component: () => import('../views/Login')},
    { path: "/login", name: 'login', component: () => import('../views/Login'),meta:{title:'登录'}},
    { path: "/register", name: 'Register', component: () => import('../views/Register'),meta:{title:'注册'}},
    { path: "/404", name: '404', component: () => import('../views/NotFound'),meta:{title:'未找到'}},
    { path: "/front", name: 'Front', component: () => import('../views/front/Front'),
      children:[
          { path: "home", name: 'Home', component: () => import('../views/front/Home'),meta:{title:'首页'}},
          { path: "bookDetail", name: 'BookDetail', component: () => import('../views/front/BookDetail'),meta:{title:'详情'}},
          { path: "borrowCart", name: 'BorrowCart', component: () => import('../views/front/BorrowCart'),meta:{title:'借阅情况'}},
          { path: "historyOder", name: 'HistoryOder', component: () => import('../views/front/HistoryOder'),meta:{title:'借阅情况'}},
          { path: "person", name: 'Person', component: () => import('../views/front/Person'),meta:{title:'个人信息'}},
          { path: "password", name: 'Password', component: () => import('../views/front/Password'),meta:{title:'修改密码'}},
          { path: "video", name: 'Video', component: () => import('../views/front/Video'),meta:{title:'播放视频'}},
          { path: "videoDetail", name: 'VideoDetail', component: () => import('../views/front/VideoDetail'),meta:{title:'播放视频'}},
          { path: "article", name: 'Article', component: () => import('../views/front/Article'),meta:{title:'论坛'}},
          { path: "articleDetail", name: 'ArticleDetail', component: () => import('../views/front/ArticleDetail'),meta:{title:'论坛'}},
      ]},
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
})

//提供一个重置路由的方法
export const resetRouter = () =>{
    router.matcher = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes,
    })
}

// 注意：刷新页面会导致页面路由重置
export const setRoutes = () => {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {
        // 获取当前的路由对象名称数组
        const currentRouteNames = router.getRoutes().map(v => v.name)
        if (!currentRouteNames.includes('Manage')) {
            // 拼装动态路由
            const manageRoute = { path: '/', name: 'Manage', component: () => import('../views/Manage.vue'), redirect: "/home", children: [
                    { path:'person',name:'个人信息',component:()=>import('../views/Person.vue')},
                    { path:'password',name:'修改密码',component:()=>import('../views/Password.vue')},
                ]}
            const menus = JSON.parse(storeMenus)
            menus.forEach(item => {
                if (item.path) {  // 当且仅当path不为空的时候才去设置路由
                    let itemMenu = {path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue')}
                    manageRoute.children.push(itemMenu)
                } else if (item.children.length) {
                    item.children.forEach(item => {
                        if (item.path) {
                            let itemMenu = {path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue')}
                            manageRoute.children.push(itemMenu)
                        }
                    })
                }
            })
            // 动态添加到现在的路由对象中去
            router.addRoute(manageRoute)
        }
    }
}
// 重置我就再set一次路由
    setRoutes()

//路由守卫
router.beforeEach((to, from, next) => {
    if (to.meta.title){
        document.title=to.meta.title
    }
    localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称，为了在Header组件中去使用
    store.commit("setPath")  // 触发store的数据更新

    if (localStorage.getItem("user")){
        if (to.path==='/home'){
            console.log('拦截了')
            if ( JSON.parse(localStorage.getItem("user")).role==='学生'){
                next("/front/home")
            }
        }
    }

    //未找到路由的情况
    if (!to.matched.length){
        const menus = localStorage.getItem("menus")
        if (menus){
            next("/404")
        }else {
            next("/login")
        }
    }
    next()  // 放行路由
})


    export default router
